<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style>
    @property --x {
      syntax: '<length>';
      inherits: false;
      initial-value: 0px;
    }
    @property --y {
      syntax: '<length>';
      inherits: false;
      initial-value: 0px;
    }
    .bezier {
      width: 40px;
      height: 40px;
      background-color: red;
      border-radius: 50%;
      margin: 400px auto;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 24px;
      font-weight: 700;
      color: #fff;
      user-select: none;
      transform: translate(var(--x), var(--y));
      animation: moveX 2s, moveY 1s;
      animation-fill-mode: forwards;
      animation-iteration-count: infinite;
      animation-timing-function: cubic-bezier(0.5, -800, 0.5, 800);
    }
    @keyframes moveX {
      to {
        --x: 1px;
      }
    }
    @keyframes moveY {
      to {
        --y: 0.1px;
      }
    }
    #trajectoryCanvas {
      width: 100%;
      height: 100dvh;
      box-sizing: border-box;
      border: 1px solid #000;
      position: absolute;
      top: 0;
      left: 0;
      /* bottom: 0;
      right: 0; */
    }
  </style>
  <body>
    <canvas id="trajectoryCanvas"></canvas>
    <div class="bezier">1</div>

    <script type="text/javascript">
      const canvas = document.querySelector('#trajectoryCanvas')
      const bezier = document.querySelector('.bezier')
      const ctx = canvas.getContext('2d')

      // 设置Canvas尺寸
      canvas.width = window.innerWidth
      canvas.height = window.innerHeight

      let path = []
      let x = 40
      let y = 40
      let dx = 2
      let dy = 2

      function animate() {
        // 获取 DOM 元素的位置并转换坐标
        const rect = bezier.getBoundingClientRect()
        const xCoord = rect.left - canvas.offsetLeft
        const yCoord = rect.top - canvas.offsetTop + bezier.offsetHeight / 2
        path.push({ x: xCoord, y: yCoord })

        // 清空 Canvas
        ctx.clearRect(0, 0, canvas.width, canvas.height)

        // 绘制运动轨迹
        ctx.beginPath()
        ctx.moveTo(path[0].x, path[0].y)
        for (let i = 1; i < path.length; i++) {
          ctx.lineTo(path[i].x, path[i].y)
        }
        ctx.strokeStyle = 'red'
        ctx.lineWidth = 2
        ctx.setLineDash([5, 5])
        ctx.stroke()

        // 更新 DOM 元素的位置
        x += dx
        y += dy

        if (x + bezier.offsetWidth > canvas.width || x < 0) {
          dx = -dx
        }
        if (y + bezier.offsetHeight > canvas.height || y < 0) {
          dy = -dy
        }

        bezier.style.left = `${x}px`
        bezier.style.top = `${y}px`

        requestAnimationFrame(animate)
      }

      // 开始动画
      animate()
    </script>
  </body>
</html>
